﻿window.noteApp = window.noteApp || {};

window.noteApp.datacontext = (function (ko) {

    var datacontext = {
        getNotes: getNotes,
        createSection: createSection,
        createNote: createNote,
        saveNewSection: saveNewSection,
        saveNewNote: saveNewNote,
        saveChangedSection: saveChangedSection,
        saveChangedNote: saveChangedNote,
        deleteSection: deleteSection,
        deleteNote: deleteNote,
        getThemeList: getThemeList,
        changeTheme : changeTheme
    };

    return datacontext;



    function getThemeList() {      
      return   ajaxRequest("get", themeUrl())
           .done(function (result) {
               config.themes = result;
           });
    }

    function changeTheme(nt,tm){
       return   ajaxRequest("put", themeUrl() + '?nt=' + nt + "&tm=" + tm);
    }

    function getNotes(notesObservable, errorObservable) {
        var options = {
            dataType: "json",
            contentType: "application/json",
            cache: false,
            type: 'get',
            data: {boardID:config.boardID}
        };

       return $.ajax(noteUrl(), options)
       // return ajaxRequest("get", noteUrl(), )
            .done(getSucceeded)
            .fail(getFailed);

        function getSucceeded(data) {
            var mappedNotes = $.map(data, function (list) { return new createNote(list); });
            notesObservable(mappedNotes);
        }

        function getFailed() {
            errorObservable("Error retrieving note lists.");
        }
    }
    function createSection(data) {
        return new datacontext.Section(data); // Section is injected by model.js
    }
    function createNote(data) {
        return new datacontext.Note(data); // Note is injected by model.js
    }
    function saveNewSection(section) {
        clearErrorMessage(section);
        return ajaxRequest("post", sectionUrl(), section)
            .done(function (result) {
                section.SectionID = result.SectionID; 
            })
            .fail(function () {
                section.ErrorMessage("Error adding a new note.");
                window.noteApp.noteViewModel.postActions();
            });
    }
    function saveNewNote(note) {
        clearErrorMessage(note);
        return ajaxRequest("post", noteUrl(), note)
            .done(function (result) {
                note.NoteID = result.NoteID;                
            })
            .fail(function () {
                note.ErrorMessage("Error adding a new note.");
                window.noteApp.noteViewModel.postActions();
            });
    }
    function deleteSection(section) {
        return ajaxRequest("delete", sectionUrl(section.SectionID))
            .fail(function () {
                section.ErrorMessage("Error removing note item.");
                window.noteApp.noteViewModel.postActions();
            });
    }
    function deleteNote(note) {
        return ajaxRequest("delete", noteUrl(note.NoteID))
            .fail(function () {
                note.ErrorMessage("Error removing note list.");
                window.noteApp.noteViewModel.postActions();
            });
    }
    function saveChangedSection(section) {
        clearErrorMessage(section);
        return ajaxRequest("put", sectionUrl(section.SectionID), section)             
            .fail(function () {
                section.ErrorMessage("Error updating note item.");
                window.noteApp.noteViewModel.postActions();
            });
    }




    function saveChangedNote(self) {
        clearErrorMessage(self);
        var note = datacontext.createNote();
        note.BoardID = config.boardID,
        note.NoteID = self.NoteID;
        note.Title = self.Title;
        note.Description = self.Description;
        note.SortIndex = self.SortIndex;
        note.Sections = self.dirtyItems();
        clearErrorMessage(note);
        return ajaxRequest("put", noteUrl(note.NoteID), note)
            .done(function (result) {
                 self.resetNote();
            })
            .fail(function () {
                self.ErrorMessage("Error: Please make sure data is valid.");
                window.noteApp.noteViewModel.postActions();
            });
    }

    // Private
    function clearErrorMessage(entity) { entity.ErrorMessage(null); }
    function ajaxRequest(type, url, data) { // Ajax helper
        var options = {
            dataType: "json",
            contentType: "application/json",
            cache: false,
            type: type,
            data: ko.toJSON(data)
        };
        return $.ajax(url, options);
    }
    // routes
    function noteUrl(id) { return "/api/apinote/" + (id || ""); }
    function sectionUrl(id) { return "/api/apisection/" + (id || ""); }
    function themeUrl() { return "/api/apitheme/"; }

})(ko);